#include "home.h"
#include "ui_home.h"
#include <userinfo.h>
#include <client.h>
#include <QtNetwork>
#include <chatdialog.h>
#include <qinputdialog.h>
#include <sendfiledialog.h>
#include <receivefiledialog.h>

extern userinfo user;
userinfo otheruser;  // 对方账号，根据我方选择不同好友，信息会被变更赋值。
QList <QString> friendlist; // 记录好友名称
QList <QString> friendiplist; // 记录好友ip
QList <QString> friendstatuelist; // 记录好友状态（是否在线。1：在线）
QList <QString> friendsendmessagelist; // 好友是否向我方发送消息
QList <QString> friendsendfilelist; // 好友是否申请向我方进行文件发送
QMap <QString, bool> temfriendlist; // 临时好友容器（名称, 是否在线）

extern QString serverIp;
extern int serverPort;
extern int tport;
extern control cont;

bool is_open_chatdialog;
int onlinenum = -1;
int listnum = -1;
int sendmessagenum = -1;
int sendfilenum = -1;
int temfnum = 0;

home::home(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::home)
{
    ui->setupUi(this);
    ui->label->setText("您好，"+ user.name); // 登录成功时赋值
    this->setWindowIcon(QIcon(":/res/comm2.png"));
    this->setWindowTitle("Boom chat");

    timer = new QTimer();
    timer->start(500);
    connect(timer,SIGNAL(timeout()),this,SLOT(Createdfriendlist()));  // 首次登录自动触发获取所有好友功能


    uniqueServer = new QTcpServer;
    uniqueServer->listen(QHostAddress::Any, tport);

    timer2 = new QTimer;

    timer2->start(1000);
    connect(uniqueServer, &QTcpServer::newConnection, [=](){
       timer2->stop();

       uniqueSocket = uniqueServer->nextPendingConnection();
       connect(uniqueSocket, &QTcpSocket::readyRead, [=](){
           QByteArray buffer = uniqueSocket->readAll();
           if("temporaryfriend" == QString(buffer).section("##", 0, 0))
           {
               QString oname = QString(buffer).section("##", 1, 1);
               for(int i = 0; i < friendlist.size(); ++i)
               {
                   if(friendlist[i] == oname)
                       return;
               }
               qDebug() << "收到通知，我为客方，需添加临时好友" << oname << endl;
               temfriendlist[oname] = true;
           }
           else if("add_friend_ok" == QString(buffer).section("##", 0, 0))
           {
               qDebug() << __LINE__ << "临时好友表：" << endl;
               auto it = temfriendlist.begin();
               while(it != temfriendlist.end())
               {
                   qDebug() << it.key() << endl;
                   ++it;
               }
               // add_friend_ok##fname
               QString fname = QString(buffer).section("##", 1, 1);
               if(!temfriendlist.remove(fname))
               {
                   qDebug() << "一个没删： " << fname <<endl;
               }
               qDebug() << __LINE__ << "临时好友表：" << endl;
               it = temfriendlist.begin();
               while(it != temfriendlist.end())
               {
                   qDebug() << it.key() << endl;
                   ++it;
               }
           }
           else
           {
               // 暂时只会收到临时对话报文
               QMessageBox::warning(this, "Warning!", "未知异常", QMessageBox::Yes);
               this->close();
               user.islogin = false;
               client *cli = new client();
               cli->show();
           }
       });
    });

    connect(timer2, &QTimer::timeout, [=](){
        timer2->stop();
        QMessageBox::warning(this, "Warning!", "网络错误1", QMessageBox::Yes);
        this->close();
        user.islogin = false;
        exit(-1);
//        client *cli = new client();
//        cli->show();
    });


    // 定时检查好友申请表
    timer3 = new QTimer;
    connect(timer3, &QTimer::timeout, [=](){
        checkFriendQuest();
    });

    // 刷新列表和检查好友申请表都是用的同一个tcpSocket，并且频率一致，会有资源争夺？
    timer3->start(700);

    fqtimer = new QTimer;
    connect(fqtimer, &QTimer::timeout, this, &this->updateButtonVisibility);

}

home::~home()
{
    timer->stop();
    timer2->stop();
    timer3->stop();
    fqtimer->stop();
    timer2->deleteLater();
    timer3->deleteLater();
    fqtimer->deleteLater();
    uniqueServer->deleteLater();
    uniqueSocket->deleteLater();
    delete ui;
}

void home::Createdfriendlist()
{
    // 事前工作，即初始化，避免异常情况。
    if(is_open_chatdialog)
    {
        // 会话窗口被打开
        ui->pushButton_startchat->setEnabled(true);
        ui->pushButton_sendmessage->setEnabled(true);
        ui->pushButton_receivefile->setEnabled(false);
        ui->pushButton_sendfile->setEnabled(false);
        ui->pushButton_rejectFile->setEnabled(true);
    }
    else if(friendlist.length() != 0 && !is_open_chatdialog)
    {
        // 用户有好友并且没有打开会话窗口
        ui->pushButton_startchat->setEnabled(true);
        ui->pushButton_sendmessage->setEnabled(true);
        ui->pushButton_receivefile->setEnabled(true);
        ui->pushButton_sendfile->setEnabled(true);
        ui->pushButton_rejectFile->setEnabled(true);
    }
    else if(friendlist.length() == 0 && !is_open_chatdialog)
    {
        // 没有好友且没有没有打开会话窗口
        ui->pushButton_startchat->setEnabled(false);
        ui->pushButton_sendmessage->setEnabled(true);
        ui->pushButton_receivefile->setEnabled(false);
        ui->pushButton_sendfile->setEnabled(false);
        ui->pushButton_rejectFile->setEnabled(false);
    }

    // 开始通信
    tcpSocket = new QTcpSocket();
    tcpSocket->abort(); // 取消已有链接
    tcpSocket->connectToHost(serverIp,serverPort);// 链接服务器
    if(!tcpSocket->waitForConnected(3000))
    {
        // 连接失败，强制下线，重新进入登录界面
        QMessageBox::warning(this, "Warning!", "网络错误2", QMessageBox::Yes);
        this->close();
        user.islogin = false;
        exit(-1);
//        client *cli = new client();
//        cli->show();
    }
    else
    {
        // 服务器连接成功
        QString message = QString("getfriendlist##%1").arg(user.id);
        tcpSocket->write(message.toUtf8());
        tcpSocket->flush();
        connect(tcpSocket,&QTcpSocket::readyRead,[=](){
            QByteArray buffer = tcpSocket->readAll();
            if(QString(buffer).section("##",0,0) == QString("getfriendlist_ok"))
            {
                //@@
                int newnum = QString(buffer).section("##",1,1).toInt();
                int newonlinenum = QString(buffer).section("##",2,2).toInt();
                int newsendmessagenum = QString(buffer).section("##",3,3).toInt();
                int newsendfilenum = QString(buffer).section("##",4,4).toInt();
                int newtemfnum = temfriendlist.size();
//                qDebug()<<newnum<<newonlinenum<<newsendfilenum<<sendfilenum<<onlinenum<<listnum;
                if(newtemfnum != temfnum || newsendmessagenum != sendmessagenum || sendfilenum != newsendfilenum || newonlinenum != onlinenum || onlinenum == -1 ||sendmessagenum==-1|| listnum==-1|| newnum!= listnum || sendfilenum == -1)
                {
                    onlinenum = newonlinenum;
                    listnum = newnum;
                    sendfilenum = newsendfilenum;
                    sendmessagenum = newsendmessagenum;
                    temfnum = newtemfnum;

                    ui->listWidget->clear();

                    // 全局变量，不清空会影响下次请求（用户刷新好友列表）
                    friendlist.clear();
                    friendiplist.clear();
                    friendstatuelist.clear();
                    friendsendmessagelist.clear();
                    friendsendfilelist.clear();

                    // 将好友写入listWidget
                    // @@
                    for(int rownum = 0;rownum < newnum ;rownum++)
                    {
                        QString friendname = QString(buffer).section("##",5+rownum*5,5+rownum*5);
                        QString friendstatue = QString(buffer).section("##",6+rownum*5,6+rownum*5);
                        QString friendip = QString(buffer).section("##",7+rownum*5,7+rownum*5);
                        QString friendsendmessage = QString(buffer).section("##",8+rownum*5,8+rownum*5);
                        QString friendsendfile = QString(buffer).section("##",9+rownum*5,9+rownum*5);
                        friendlist.append(friendname);
                        friendstatuelist.append(friendstatue);
                        friendiplist.append(friendip);
                        friendsendmessagelist.append(friendsendmessage);
                        friendsendfilelist.append(friendsendfile);

                        qDebug() << "联系人名称：" << friendname << endl;

                        QString prefix = "("; // 前缀

                        if(friendstatue == "1")
                        {
                            // nt
                            if(temfriendlist.count(friendname))
                            {
                                prefix += "临时好友";
                            }
                            if(friendsendmessage == "1")
                            {
                                if(friendsendfile == "1")
                                {
                                    ui->listWidget->insertItem(rownum,tr((friendname + prefix + "在线，想给您发文件，有新消息)").toUtf8()));
                                }
                                else
                                {
                                    ui->listWidget->insertItem(rownum,tr((friendname + prefix + "在线，有新消息)").toUtf8()));
                                }
                            }
                            else
                            {
                                if(friendsendfile == "1")
                                {
                                    ui->listWidget->insertItem(rownum,tr((friendname + prefix + "在线，想给您发文件)").toUtf8()));
                                }
                                else
                                {
                                    ui->listWidget->insertItem(rownum,tr((friendname + prefix + "在线)").toUtf8()));
                                }
                            }

                        }
                        else
                        {
                            if(friendsendmessage == "1")
                            {
                                ui->listWidget->insertItem(rownum,tr((friendname + "(不在线，有新消息)").toUtf8()));
                            }
                            else
                            {
                                ui->listWidget->insertItem(rownum,tr((friendname + "(不在线)").toUtf8()));
                            }

                            if(temfriendlist.count(friendname))
                            {
                                qDebug() << __LINE__ << "临时好友表：" << endl;
                                auto it = temfriendlist.begin();
                                while(it != temfriendlist.end())
                                {
                                    qDebug() << it.key() << endl;
                                    ++it;
                                }
                                // 离线的临时好友
                                temfriendlist[friendname] = false; // 刷新有延迟，照顾延迟。

                                onlineDelFriend(friendname);
                            }
                        }
                    }

                    ui->pushButton_deletepeople->setEnabled(true);
                    if(!is_open_chatdialog)
                    {
                        ui->pushButton_startchat->setEnabled(true);
                        ui->pushButton_receivefile->setEnabled(true);
                        ui->pushButton_sendfile->setEnabled(true);
                    }
                }
            }
            else if(QString(buffer).section("##",0,0)==QString("getfriendlist_error"))
            {
                // 全局变量，不清空会影响下次请求（用户刷新好友列表）
                friendlist.clear();
                friendiplist.clear();
                friendstatuelist.clear();
                friendsendmessagelist.clear();
                friendsendfilelist.clear();
                if( listnum == -1 || 0!= listnum)
                {
                    listnum = 0;
                    ui->listWidget->clear();
                    ui->listWidget->insertItem(0,tr("暂无好友"));
                }
                ui->pushButton_startchat->setEnabled(false);
                ui->pushButton_deletepeople->setEnabled(false);
                ui->pushButton_receivefile->setEnabled(false);
                ui->pushButton_sendfile->setEnabled(false);
            }
        });
    }
}

// 临时对话
void home::on_pushButton_sendmessage_clicked()
{
    // 发信息
    if(ui->lineEdit_sendname->text()!="" && ui->lineEdit_sendname->text() != user.name)
    {
        for(int i = 0; i < friendlist.size(); ++i)
        {
            // 如果临时对话中输入的是联系人的名称，那就走正常的对话逻辑，不要把联系人调整为临时好友
            if(friendlist.at(i) == ui->lineEdit_sendname->text())
            {
                chatFriendFromtemChat(ui->lineEdit_sendname->text());
                return;
            }
        }

        // 发送人名不为空,且不能给自己发送消息
        tcpSocket = new QTcpSocket();
        tcpSocket->abort();//取消已有链接
        tcpSocket->connectToHost(serverIp, serverPort);// 链接服务器
        if(!tcpSocket->waitForConnected(30000))
        {
            QMessageBox::warning(this, "Warning!", "网络错误3", QMessageBox::Yes);
            user.islogin = false;
            exit(-1);
//            client *cli = new client();
//            cli->show();
        }
        else
        {
            //服务器连接成功
            qDebug() << "临时对话申请，我方id = " << user.id << endl;
            QString message = QString("temporarysendmessage##%1##%2").arg(user.id).arg(ui->lineEdit_sendname->text());
            tcpSocket->write(message.toUtf8());
            tcpSocket->flush();

            connect(tcpSocket,&QTcpSocket::readyRead,[=](){
                QByteArray buffer = tcpSocket->readAll();
                if( QString(buffer).section("##",0,0) == QString("temporarysendmessage_ok"))
                {
                    // 查有此人，并且在线，可以发消息
                    // 添加临时好友
                    otheruser.id = QString(buffer).section("##",1,1).toInt();
                    otheruser.name = ui->lineEdit_sendname->text();
                    ui->lineEdit_sendname->clear();
                    chatdialog *cht = new chatdialog(otheruser.id, otheruser.name);
                    cht->setAttribute(Qt::WA_DeleteOnClose); // 设置从窗口在关闭时自动删除
                    cht->show();
                }
                else if( QString(buffer).section("##",0,0) == QString("temporarysendmessage_offline"))
                {
                    QMessageBox::warning(this, "Warning!", "对方未上线，无法发起临时对话", QMessageBox::Yes);
                    ui->lineEdit_sendname->clear();
                    // 重新聚焦
                    ui->lineEdit_sendname->setFocus();
                }
                else if( QString(buffer).section("##",0,0) == QString("temporarysendmessage_error"))
                {
                    QMessageBox::warning(this, "Warning!", "该用户不存在", QMessageBox::Yes);
                    ui->lineEdit_sendname->clear();
                    // 重新聚焦
                    ui->lineEdit_sendname->setFocus();
                }
            });
        }
    }
    else if(ui->lineEdit_sendname->text() == user.name)
    {
        QMessageBox::warning(this, "Warning!", "不能给自己发消息", QMessageBox::Yes);
        ui->lineEdit_sendname->clear();
        ui->lineEdit_sendname->setFocus();
    }
    else
    {
        QMessageBox::warning(this, "Warning!", "用户名不能为空", QMessageBox::Yes);
        ui->lineEdit_sendname->clear();
        ui->lineEdit_sendname->setFocus();
    }
}

void home::on_pushButton_quit_clicked()
{
    // 退出登录
    this->close();
    user.islogin = false;
    // 回到登录界面
    client *cli = new client();
    cli->show();
}

// 添加联系人（好友）
void home::on_pushButton_addpeople_clicked()
{
    // add_friend##uid##uname##fname
    bool ok;
    QString addfriendname = QInputDialog::getText(this, tr("增添联系人"),tr("请输入对方昵称"), QLineEdit::Normal,0,&ok);
    if (ok && !addfriendname.isEmpty())
    {
        if(addfriendname != user.name)
        {
            bool quit = false;
            // 判断是否已经是好友且不是临时好友
            for(int i = 0; i < friendlist.size(); ++i)
            {
                if(friendlist.at(i) == addfriendname && temfriendlist.find(addfriendname) == temfriendlist.end())
                {
                    if(friendlist.at(i) == addfriendname)
                    {
                        qDebug() << "friendlist.at(i): " << friendlist.at(i) << ", addfriendname: " << addfriendname << endl;
                    }
                    if(temfriendlist.find(addfriendname) == temfriendlist.end())
                    {
                        qDebug() << "不是临时好友" << endl;
                    }
                    QMessageBox::information(this, "Information", "对方已是您的好友");
                    quit = true;
                    break;
                }
            }
            if(!quit)
            {
                tcpSocket = new QTcpSocket();
                tcpSocket->abort();// 取消已有链接
                tcpSocket->connectToHost(serverIp, serverPort);// 链接服务器
                if(!tcpSocket->waitForConnected(30000))
                {
                    QMessageBox::warning(this, "Warning!", "网络错误4", QMessageBox::Yes);
                    this->close();
                    user.islogin = false;
                    exit(-1);
//                    client *cli = new client();
//                    cli->show();
                }
                else
                {
                    // 服务器连接成功
                    QString message = QString("add_friend##%1##%2##%3").arg(user.id).arg(user.name).arg(addfriendname);

                    tcpSocket->write(message.toUtf8());
                    tcpSocket->flush();

                    connect(tcpSocket,&QTcpSocket::readyRead,[=](){
                        QByteArray buffer = tcpSocket->readAll();
                        qDebug() << QString(buffer);
                        if( QString(buffer).section("##",0,0) == QString("add_friend_ok"))
                        {
                            // 加好友 @@
                            //                        onlinenum = -1;

                            //                        // 如果他之前是临时好友，并且我还没退出本次登录，为了避免他还是显示为临时好友，从临时好友容器中删去
                            //                        auto it = temfriendlist.find(addfriendname);
                            //                        if(it != temfriendlist.end())
                            //                            temfriendlist.erase(it);

                            // 请求成功
                            qDebug() << "服务端已收到添加好友申请，请等待对方同意..." << endl;
                        }
                        else if( QString(buffer).section("##",0,0) == QString("add_friend_error"))
                        {
                            QMessageBox::warning(this, "Warning!", "查无此人", QMessageBox::Yes);
                        }
                    });
                }
            }
        }
        else
        {
            QMessageBox::warning(this, "Warning!", "不能添加自己", QMessageBox::Yes);
        }
    }
}


// 开始对话
void home::on_pushButton_startchat_clicked()
{
    // 选中了某项（某个好友）
    if(ui->listWidget->currentRow() != -1)
    {
        QString friendname = friendlist.at(ui->listWidget->currentRow()); // 当前选中行

        tcpSocket = new QTcpSocket();
        tcpSocket->abort(); // 取消已有链接
        tcpSocket->connectToHost(serverIp, serverPort); // 链接服务器
        if(!tcpSocket->waitForConnected(30000))
        {
            QMessageBox::warning(this, "Warning!", "网络错误6", QMessageBox::Yes);
            this->close();
            user.islogin = false;
            exit(-1);
//            client *cli = new client();
//            cli->show();
        }
        else
        {
            // 服务器连接成功
            QString message = QString("wantsendmessage##%1##%2").arg(user.id).arg(friendname);
            tcpSocket->write(message.toUtf8());
            tcpSocket->flush();

            connect(tcpSocket,&QTcpSocket::readyRead,[=](){
                QByteArray buffer = tcpSocket->readAll();
                if(QString(buffer).section("##",0,0) == QString("wantsendmessage_ok"))
                {
                    // 进一步判断是否是已下线的临时好友
                    if(temfriendlist.count(friendname) && !temfriendlist[friendname])
                    {
                        QMessageBox::information(this, "info", "无法与离线的临时好友对话");
                        return; // 77
                    }

                    // 查有此人，可以发消息
                    otheruser.id = QString(buffer).section("##",1,1).toInt();
                    otheruser.name = friendname;
                    ui->pushButton_startchat->setEnabled(false);
                    chatdialog *cht = new chatdialog(otheruser.id, otheruser.name);
                    cht->show();
                }
            });
        }
    }
    else
    {
        QMessageBox::warning(this, "Warning!", "您未选择联系人", QMessageBox::Yes);
    }
}


// 开始对话（从临时对话处进入与联系人的对话）
void home::chatFriendFromtemChat(QString fname)
{
    tcpSocket = new QTcpSocket();
    tcpSocket->abort(); // 取消已有链接
    tcpSocket->connectToHost(serverIp, serverPort); // 链接服务器
    if(!tcpSocket->waitForConnected(30000))
    {
        QMessageBox::warning(this, "Warning!", "网络错误6", QMessageBox::Yes);
        this->close();
        user.islogin = false;
        exit(-1);
//        client *cli = new client();
//        cli->show();
    }
    else
    {
        // 服务器连接成功
        QString message = QString("wantsendmessage##%1##%2").arg(user.id).arg(fname);
        tcpSocket->write(message.toUtf8());
        tcpSocket->flush();

        connect(tcpSocket,&QTcpSocket::readyRead,[=](){
            QByteArray buffer = tcpSocket->readAll();
            if(QString(buffer).section("##",0,0) == QString("wantsendmessage_ok"))
            {
                // 进一步判断是否是已下线的临时好友
                if(temfriendlist.count(fname) && !temfriendlist[fname])
                {
                    QMessageBox::information(this, "info", "无法与离线的临时好友对话");
                    return; // 77
                }

                // 查有此人，可以发消息
                otheruser.id = QString(buffer).section("##",1,1).toInt();
                otheruser.name = fname;
                ui->pushButton_startchat->setEnabled(false);
                chatdialog *cht = new chatdialog(otheruser.id, otheruser.name);
                cht->show();
            }
        });
    }
}


// 删除好友（联系人）
void home::on_pushButton_deletepeople_clicked()
{
    if(ui->listWidget->currentRow()!=-1)
    {
        QString friendname = friendlist.at(ui->listWidget->currentRow());

        if(temfriendlist.find(friendname) != temfriendlist.end())
        {
            QMessageBox::information(this, "通知", "对方是您的临时好友，无需手动删除，下线时将自动删除");
        }
        else
        {
            QString dlgTitle="提示";
            QString strInfo="您将删除好友："+friendname+"\n确定吗？";
            // QMessageBox::StandardButton  defaultBtn = QMessageBox::NoButton; // 默认就是NoButton
            QMessageBox::StandardButton result;
            // result = QMessageBox::question(this, dlgTitle, strInfo,QMessageBox::Cancel|QMessageBox::Yes);
            result = QMessageBox::question(this, dlgTitle, strInfo, QMessageBox::Cancel | QMessageBox:: Yes);
            if (result == QMessageBox::Yes)
            {
                tcpSocket = new QTcpSocket();
                tcpSocket->abort(); // 取消已有链接
                tcpSocket->connectToHost(serverIp, serverPort); // 链接服务器
                if(!tcpSocket->waitForConnected(30000))
                {
                    QMessageBox::warning(this, "Warning!", "网络错误7", QMessageBox::Yes);
                    this->close();
                    user.islogin = false;
                    exit(-1);
//                    client *cli = new client();
//                    cli->show();
                }
                else
                {
                    //服务器连接成功
                    QString message = QString("delete_friend##%1##%2").arg(user.id).arg(friendname);
                    tcpSocket->write(message.toUtf8());
                    tcpSocket->flush();

                    connect(tcpSocket,&QTcpSocket::readyRead,[=](){
                        QByteArray buffer = tcpSocket->readAll();
                        if( QString(buffer).section("##",0,0) == QString("delete_friend_ok"))
                        {
                            // 刷新好友列表
                            Createdfriendlist();
                        }
                    });
                }
            }
        }
    }
    else
    {
        QMessageBox::warning(this, "Warning!", "您未选择联系人", QMessageBox::Yes);
    }
}


// 离线删除临时好友
void home::delTemFriend()
{
    tcpSocket = new QTcpSocket();
    tcpSocket->abort(); // 取消已有链接
    tcpSocket->connectToHost(serverIp, serverPort); // 链接服务器
    if(!tcpSocket->waitForConnected(30000))
    {
        QMessageBox::warning(this, "Warning!", "网络错误8", QMessageBox::Yes);
        this->close();
        user.islogin = false;
        exit(-1);
//        client *cli = new client();
//        cli->show();
    }
    else
    {
        //服务器连接成功
        qDebug() << "离线删除临时好友: " << endl;
        auto it = temfriendlist.begin();
        while(it != temfriendlist.end())
        {
            QString dname = it.key();
            qDebug() << dname << endl;
            QString message = QString("delete_friend##%1##%2").arg(user.id).arg(dname);
            tcpSocket->write(message.toUtf8());
            tcpSocket->flush();
            ++it;
        }
    }
}

// 我方在线，临时好友下线，删除临时好友
void home::onlineDelFriend(QString delFName)
{
    tcpSocket = new QTcpSocket();
    tcpSocket->abort(); // 取消已有链接
    tcpSocket->connectToHost(serverIp, serverPort); // 链接服务器
    if(!tcpSocket->waitForConnected(30000))
    {
        QMessageBox::warning(this, "Warning!", "网络错误9", QMessageBox::Yes);
        this->close();
        user.islogin = false;
        exit(-1);
//        client *cli = new client();
//        cli->show();
    }
    else
    {
        //服务器连接成功
        QString message = QString("delete_friend##%1##%2").arg(user.id).arg(delFName);
        tcpSocket->write(message.toUtf8());
        tcpSocket->flush();
    }
}



// 发送文件
void home::on_pushButton_sendfile_clicked()
{
    // 选中好友
    if(ui->listWidget->currentRow() != -1)
    {
        if(friendstatuelist.at(ui->listWidget->currentRow()) == "1")
        {
            QString friendname = friendlist.at(ui->listWidget->currentRow());
            qDebug() << friendname;
            otheruser.name = friendname;
            otheruser.ip = friendiplist.at(ui->listWidget->currentRow());

            tcpSocket = new QTcpSocket();
            tcpSocket->abort(); // 取消已有链接
            tcpSocket->connectToHost(serverIp, serverPort); // 链接服务器
            if(!tcpSocket->waitForConnected(30000))
            {
                QMessageBox::warning(this, "Warning!", "网络错误10", QMessageBox::Yes);
                this->close();
                user.islogin = false;
                exit(-1);
//                client *cli = new client();
//                cli->show();
            }
            else
            {
                // 服务器连接成功
                QString message = QString("want_send_file##%1##%2").arg(user.id).arg(friendname);
                tcpSocket->write(message.toUtf8());
                tcpSocket->flush();
            }
            sendfiledialog *sf = new sendfiledialog;
            sf->show();
        }
        else
        {
            QMessageBox::warning(this, "Warning!", "联系人未在线无法发送文件", QMessageBox::Yes);
        }
    }
    else
    {
        QMessageBox::warning(this, "Warning!", "您未选择联系人", QMessageBox::Yes);
    }
}

void home::on_pushButton_receivefile_clicked()
{
    // 选中好友
    if(ui->listWidget->currentRow() != -1)
    {
        // 接收文件的前提是对方向我方申请发送文件
        if(friendsendfilelist.at(ui->listWidget->currentRow()) == "1")
        {
            QString friendname = friendlist.at(ui->listWidget->currentRow());
            otheruser.name = friendname;
            otheruser.ip = friendiplist.at(ui->listWidget->currentRow());
            receivefiledialog *rf = new receivefiledialog;
            rf->show();
        }
        else
        {
            QMessageBox::warning(this, "Warning!", "该联系人未给您发送文件", QMessageBox::Yes);
        }
    }
    else
    {
        QMessageBox::warning(this, "Warning!", "您未选择联系人", QMessageBox::Yes);
    }
}

// 窗口关闭事件
void home::closeEvent(QCloseEvent *event)
{
    emit cont.allquit();

    timer->stop();
    tcpSocket = new QTcpSocket();
    tcpSocket->abort(); // 取消已有链接
    tcpSocket->connectToHost(serverIp, serverPort); // 链接服务器
    // @@
    if(!tcpSocket->waitForConnected(30000))
    {
        this->close();
        user.islogin = false;
    }
    else
    {
        //服务器连接成功
        QString message = QString("logout##%1").arg(user.id);
        tcpSocket->write(message.toUtf8());
        tcpSocket->flush();
        QMessageBox::warning(this, "Success", "下线成功, 已删除所有临时好友", QMessageBox::Yes);
        delTemFriend(); // 删除所有临时好友
    }
}

// 刷新
void home::on_pushButton_fresh_clicked()
{
    onlinenum = -1;
    listnum = -1;
    sendmessagenum = -1;
    sendfilenum = -1;
}

// 检查好友申请表
void home::checkFriendQuest()
{
    // 有bug就加个初始化(CreatF)

    // 开始通信
    tcpSocket = new QTcpSocket();
    tcpSocket->abort(); // 取消已有链接
    tcpSocket->connectToHost(serverIp,serverPort);// 链接服务器
    if(!tcpSocket->waitForConnected(3000))
    {
        // 连接失败，强制下线，重新进入登录界面
        QMessageBox::warning(this, "Warning!", "网络错误11", QMessageBox::Yes);
        this->close();
        user.islogin = false;
        exit(-1);
//        client *cli = new client();
//        cli->show();
    }
    else
    {
        // 服务器连接成功
        // checkfriendquest##userid
        QString request = "getfriendquest##" + QString::number(user.id);
        tcpSocket->write(request.toUtf8());
        tcpSocket->flush();
        connect(tcpSocket, &QTcpSocket::readyRead, [=](){
            QByteArray buffer = tcpSocket->readAll();
            if("getfriendquest_ok" == QString(buffer).section("##", 0, 0))
            {
                // 闪烁图标
                fqtimer->start(500);
            }
            else
            {
                // 停止闪烁, 并显示图标
                if(fqtimer->isActive())
                {
                    fqtimer->stop();
                    ui->pushButton_friend_requests->show();
                }
            }
        });
    }
}


// 显示好友申请列表
void home::on_pushButton_friend_requests_clicked()
{
    friendquest* fqlist = new friendquest(user.id);
    fqlist->show();
}

void home::updateButtonVisibility()
{
    if (ui->pushButton_friend_requests->isHidden())
            QMetaObject::invokeMethod(ui->pushButton_friend_requests, "show");
        else
            QMetaObject::invokeMethod(ui->pushButton_friend_requests, "hide");
}

void home::on_pushButton_rejectFile_clicked()
{
    // 选中好友
    if(ui->listWidget->currentRow() != -1)
    {
        // 拒绝文件的前提是对方向我方申请发送文件
        if(friendsendfilelist.at(ui->listWidget->currentRow()) == "1")
        {
            QString friendname = friendlist.at(ui->listWidget->currentRow());
            otheruser.name = friendname;
            otheruser.ip = friendiplist.at(ui->listWidget->currentRow());
            QString oip = otheruser.ip;
            qint16 oport = 9988;
            QTcpSocket* temSocket = new QTcpSocket;
            temSocket->connectToHost(oip, oport);
            if(!temSocket->waitForConnected(3000))
            {
                // 连接失败，强制下线，重新进入登录界面
                QMessageBox::warning(this, "Warning!", "网络错误11", QMessageBox::Yes);
                this->close();
                user.islogin = false;
                exit(-1);
            }
            else
            {
                // 连接成功
                temSocket->write("rejectFile");
                temSocket->flush();
                delete temSocket;
                temSocket = nullptr;
            }

            tcpSocket = new QTcpSocket();
            tcpSocket->abort();
            tcpSocket->connectToHost(oip, oport);
            QString message = QString("send_ok");
            tcpSocket->write(message.toUtf8());
            tcpSocket->flush();
            tcpSocket->disconnectFromHost();
            tcpSocket->close();

            tcpSocket = new QTcpSocket();
            tcpSocket->abort(); // 取消已有链接
            tcpSocket->connectToHost(serverIp, serverPort); // 链接服务器
            if(!tcpSocket->waitForConnected(30000))
            {
                this->close();
                user.islogin = false;
            }
            else
            {
                // 服务器连接成功
                // @@
                QString loginmessage = QString("send_file_ok##%1##%2").arg(user.id).arg(otheruser.name);
                qDebug()<<loginmessage;
                tcpSocket->write(loginmessage.toUtf8());
                tcpSocket->flush();
                is_open_chatdialog = false;
            }
            tcpSocket->disconnectFromHost();
            tcpSocket->close();
        }
        else
        {
            QMessageBox::warning(this, "Warning!", "该联系人未给您发送文件", QMessageBox::Yes);
        }
    }
    else
    {
        QMessageBox::warning(this, "Warning!", "您未选择联系人", QMessageBox::Yes);
    }
}
